<?php

namespace app\agent\controller\statistics;

use app\agent\model\User;
use app\admin\model\wallet\Record;
use app\agent\library\Backend;

/**
 * 统计管理
 *
 * @icon fa fa-bar-chart
 * @remark 可以查看评论相关统计信息
 */
class Statistics extends Backend
{

    /**
     * 模型对象
     */
    protected $model = null;
    protected $cids = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->cids = User::where('pid',$this->auth->id)->column('id');
    }

    /**
     * 查询统计
     * 总投注，总上分，总提款，总赠送
     */
    public function index()
    {
        $date = $this->request->post();

        $data = $this->getOrderStatisticsData($date);
        $statistics = ['columns' => array_keys($data['list']), 'data' => array_values($data['list']),'statistics'=>$data['statistics']];
        if ($this->request->isPost()) {
            $this->success('', '', $statistics);
        }

        $statistics['totalbets']    = number_format(Record::where('type',3)->whereIn('user_id',$this->cids)->sum('money'),2);//下注
        $statistics['totalupscore'] = number_format(Record::where('type',1)->whereIn('user_id',$this->cids)->sum('money'),2);//上分
        $statistics['totalwithdraw']= number_format(Record::where('type',2)->whereIn('user_id',$this->cids)->sum('money'),2);//提现
        $statistics['totalgive']    = number_format(10000,2);//赠送

        $statistics['todaybets']   = number_format(Record::where('type',3)->whereIn('user_id',$this->cids)->whereTime('createtime', 'today')->sum('money'),2);//今日下注
        $statistics['todayupscore']= number_format(Record::where('type',1)->whereIn('user_id',$this->cids)->whereTime('createtime', 'today')->sum('money'),2);//今日上分
        $statistics['todaywithdraw']= number_format(Record::where('type',2)->whereIn('user_id',$this->cids)->whereTime('createtime', 'today')->sum('money'),2);//今日提现
        $statistics['totaygive']   = number_format(5000,2);//赠送
        $this->view->assign('statistics', $statistics);
        $this->assignconfig('statistics', $statistics);
        return $this->view->fetch();
    }

    /**
     * 获取订单统计数据
     * @param string $date
     * @return array
     */
    protected function getOrderStatisticsData($data = '')
    {

        $date = isset($data['date']) ? $data['date'] : '';
        $user_ids = User::where('group_id',2)->column('id');

        if( isset($data['account']) && $data['account'] ){
            $user_ids = User::where('username','=',$data['account'])->where('pid',$this->auth->id)->column('id');
        }else{
            $user_ids = User::where('group_id',2)->where('pid',$this->auth->id)->column('id');
        }
        $statistics = ['upscore'=>0,'withdraw'=>0,'bets'=>0,'give'=>0];
        if ($date) {
            list($start, $end) = explode(' - ', $date);

            $starttime = strtotime($start);
            $endtime = strtotime($end);
        } else {
            $starttime = \fast\Date::unixtime('day', 0, 'begin');
            $endtime = \fast\Date::unixtime('day', 0, 'end');
        }
        $totalseconds = $endtime - $starttime;

        $format = '%Y-%m-%d';
        if ($totalseconds > 86400 * 30 * 2) {
            $format = '%Y-%m';
        } else if ($totalseconds > 86400) {
            $format = '%Y-%m-%d';
        } else {
            $format = '%H:00';
        }
        $betslist = Record::where('createtime', 'between time', [$starttime, $endtime])->where('type',3)
            ->whereIn('user_id',$user_ids)
            ->field('createtime, money, SUM(money) AS nums, MIN(createtime) AS min_createtime, MAX(createtime) AS max_createtime,
            DATE_FORMAT(FROM_UNIXTIME(createtime), "' . $format . '") AS bets_date')
            ->group('bets_date')
            ->select();//投注


        $lists = Record::where('createtime', 'between time', [$starttime, $endtime])
            ->whereIn('user_id',$user_ids)
            ->where('pay_status',1)
            ->field('SUM(money) as nums,type')
            ->group('type')
            ->select();//投注

        $zhongjiang = 0;
        $xiazhu = 0;
        $upscore = 0;
        $downscore = 0;
        foreach ( $lists as $list ){
            if( $list['type'] == 1 || $list['type'] == 7 || $list['type'] == 8 ){
                $upscore +=$list['nums'];
                //$statistics['upscore'] = substr(sprintf("%.3f",$upscore),0,-1);
            }
            if( $list['type'] == 2 ){
                $statistics['withdraw'] = $list['nums'];
            }
            if( $list['type'] == 3 ){
                $statistics['bets'] = $list['nums'];
                $xiazhu = $xiazhu + $list['nums'];
            }
            if( $list['type'] == 5 ){
                $statistics['give'] = $list['nums'];
            }
            if( $list['type'] == 4 ){
                $zhongjiang += $zhongjiang + $list['nums'];
            }
            if( $list['type'] == 9 ){
                $downscore += $downscore+$list['nums'];
            }
        }

        $statistics['upscore'] = substr(sprintf("%.3f",$upscore-$downscore),0,-1);

        $statistics['profit'] = substr(sprintf("%.3f",$xiazhu-$zhongjiang+$downscore),0,-1);//平台
        //$statistics['grprofit'] = substr(sprintf("%.3f",$zhongjiang-$xiazhu),0,-1);//个人
        if ($totalseconds > 84600 * 30 * 2) {
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $column[] = date('Y-m', $starttime);
            }
        } else if ($totalseconds > 86400) {
            for ($time = $starttime; $time <= $endtime;) {
                $column[] = date("Y-m-d", $time);
                $time += 86400;
            }
        } else {
            for ($time = $starttime; $time <= $endtime;) {
                $column[] = date("H:00", $time);
                $time += 3600;
            }
        }
        $list = array_fill_keys($column, 0);
        foreach ($betslist as $k => $v) {
            $list[$v['bets_date']] = $v['nums'];
        }
        return ['list'=>$list,'statistics'=>$statistics];

    }


}
